# -*- coding: utf-8 -*-

import json
from public_util.util.AutoUrl import Route
from django.http import HttpResponse, Http404
from django.shortcuts import render_to_response
from package.models import Version, Branch, Project, Task, Handle


@Route()
def version(request):
    """版本CRUD接口"""
    if request.method == "GET":
        req = request.REQUEST.get
        init = req("init", 0)
        if init:
            plat_type = Version.MOBILE_OS_TYPE
            pro_objs = Project.filter_project(request)
            bra_objs = Branch.filter_project(request)
            return render_to_response("version/version_index.html", locals())
        else:
            # state_type = Version.STATE_TYPE
            os_type = Version.OS_TYPE
            ver_objs = Version.filter_record(request)
            item_list = []
            for obj in ver_objs:
                item_list.append([obj.branch.project.pro_name, obj.ver_name, obj.branch.branch_name,
                                  obj.get_os_type_display(), obj.res_svn,
                                  obj.create_time.strftime("%Y-%m-%d %H:%M:%S"), obj.id])
            return HttpResponse(json.dumps({"aaData": item_list}), content_type="application/json")
    elif request.method == "POST":
        err_msg = ""
        params = request.post_dic
        try:
            params["branch"] = Branch.objects.filter(id=params.get("branch", 0)).first()
            Version(**params).save()
        except Exception as e:
            err_msg = e
        return render_to_response("feedback.html", locals())
    # elif request.method == "PUT":
    #     params = request.get_dic
    #     v_id = params.pop("id", 0)
    #     ver_objs = Version.objects.filter(id=v_id)
    #     ver_objs.update(**params)
    #     return render_to_response("feedback.html", locals())
    elif request.method == "DELETE":
        err_msg = ""
        v_id = request.REQUEST.get("id", 0)
        v_obj = Version.objects.filter(id=v_id).first()
        try:
            Handle.create_handle(
                user_id=request.admin.id,
                user=request.admin.alias,
                ope_id=10,
                pro_name=v_obj.branch.project.pro_name,
                branch_name=v_obj.branch.branch_name,
                res_svn=v_obj.res_svn,
                os_type=v_obj.get_os_type_display()
            )
            v_obj.delete()
        except Exception as e:
            err_msg = e
        return render_to_response("feedback.html", locals())


@Route()
def version_detail(request):
    """版本详情页面接口"""
    # state_type = Version.STATE_TYPE
    os_type = Version.OS_TYPE
    bra_tuple = Branch.filter_project(request).values_list("id", "branch_name")
    redo = request.REQUEST.get("redo", 0)
    v_id = request.REQUEST.get("id", 0)
    if v_id:
        model = Version.objects.filter(id=v_id).first()
    return render_to_response("version/version_detail.html", locals())
